package com.hrb.douban.activtity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hrb.commonsdk.okhttp.listener.DisposeDataListener;
import com.hrb.commonsdk.okhttp.request.RequestParams;
import com.hrb.douban.CustomApplication;
import com.hrb.douban.OnItemClickListener;
import com.hrb.douban.R;
import com.hrb.douban.activtity.base.BaseActivity;
import com.hrb.douban.adapter.ComingAdapter;
import com.hrb.douban.constant.ConstantCode;
import com.hrb.douban.constant.HttpConstants;
import com.hrb.douban.network.RequestCenter;
import com.hrb.douban.record.Comingrecord;
import com.hrb.douban.record.SubjectsBean;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SearchResultActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.search_result_title)
    TextView searchResultTitle;
    @BindView(R.id.search_result_back_icons)
    ImageView searchResultBackIcons;
    @BindView(R.id.search_result_header)
    RelativeLayout searchResultHeader;
    @BindView(R.id.search_result_recycler_view)
    RecyclerView searchResultRecyclerView;
    @BindView(R.id.search_result_swipe_refresh)
    SmartRefreshLayout searchResultSwipeRefresh;

    private int scrollY = 0;
    private ComingAdapter adapter;
    private int start = 0;
    private int lastPosition = 0;
    private int lastOffset = 0;
    private String categorytag="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);
        ButterKnife.bind(this);
        categorytag= getIntent().getStringExtra("category");
        start=0;
        searchResultTitle.setText(categorytag);
        searchResultBackIcons.setOnClickListener(this);
        GridLayoutManager gridLayoutManager=new GridLayoutManager(getApplicationContext(),2);
        searchResultRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //Log.d("messageDY : ", dy + "");
                scrollY += dy;
                if (scrollY > 100) {
                    //thirdTitleBar.setVisibility(View.GONE);
                }else{
                    //thirdTitleBar.setVisibility(View.VISIBLE);
                }
                //Log.d("message : ", scrollY + "");
            }
        });
        searchResultRecyclerView.setLayoutManager(gridLayoutManager);
        /**
         * 记录recyclerView 在视图的位置添加滚动事件
         */
        searchResultRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(recyclerView.getLayoutManager() != null) {
                    getPositionAndOffset();
                }
            }
        });
        //关闭下拉
        searchResultSwipeRefresh.setEnableRefresh(false);
        //底部信息
        searchResultSwipeRefresh.setRefreshFooter(new ClassicsFooter(CustomApplication.getContext()));
        searchResultSwipeRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                RequestParams params=new RequestParams();
                params.put("tag",categorytag);
                params.put("start",start+"");
                params.put("count","20");
                requestData(params);
                //requestData(null);
                searchResultSwipeRefresh.finishLoadMore(2000);
            }
        });
        RequestParams params=new RequestParams();
        params.put("tag",categorytag);
        params.put("start",start+"");
        params.put("count","20");
        requestData(params);
    }
    private void requestData(RequestParams params) {
        RequestCenter.getRequest(HttpConstants.SEARCH_ROOT , params, Comingrecord.class, new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                Comingrecord comingrecord=(Comingrecord)responseObj;

                if(responseObj!=null&&comingrecord.getCount()>0){
                    if(start==0){
                        adapter=new ComingAdapter(comingrecord.getSubjects());
                    }else{
                        adapter.add(comingrecord.getSubjects());
                    }
                    start+=comingrecord.getSubjects().size();
                    View footer = (View) LayoutInflater.from(getApplicationContext()).inflate(R.layout.coming_footer, searchResultRecyclerView, false);
                    TextView textView=footer.findViewById(R.id.coming_bottom_message);
                    if(start==comingrecord.getTotal()){
                        textView.setText("没有更多了");
                        searchResultSwipeRefresh.setNoMoreData(true);
                    }else{
                        textView.setText("加载更多");
                    }
                    adapter.setFooterView(footer);
                    adapter.setOnItemClickListener(new OnItemClickListener() {
                        SubjectsBean subjectsBean;
                        @Override
                        public void onItemClick(View view, int position) {
                            subjectsBean = adapter.getSubjects().get(position);
                            Intent intent=new Intent(getApplicationContext(),FilmDetailsActivity.class);
                            intent.putExtra("id",subjectsBean.getId());
                            startActivityForResult(intent,ConstantCode.requestCode);
                        }

                        @Override
                        public void onCategoryClick(View view, String category) {

                        }
                    });
                    searchResultRecyclerView.setAdapter(adapter);
                    scrollToPosition();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {

            }
        });
    }
    /**
     * 让searchResultRecyclerView滚动到指定位置
     */
    private void scrollToPosition() {
        if(searchResultRecyclerView.getLayoutManager() != null && lastPosition >= 0) {
            ((LinearLayoutManager) searchResultRecyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
        }
    }
    /**
     * 记录RecyclerView当前位置
     */
    private void getPositionAndOffset() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) searchResultRecyclerView.getLayoutManager();
        //获取可视的第一个view
        View topView = layoutManager.getChildAt(0);
        if(topView != null) {
            //获取与该view的顶部的偏移量
            lastOffset = topView.getTop();
            //得到该View的数组位置
            lastPosition = layoutManager.getPosition(topView);
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_result_back_icons:
                /*Intent backIntent = new Intent(this, MainActivity.class);
                backIntent.putExtra("name", 1);
                //FilmDetailsActivity.this.setResult(ConstantCode.resultCode, backIntent);
                startActivity(backIntent);*/
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode== KeyEvent.KEYCODE_BACK){
            /*Intent backIntent = new Intent(this, MainActivity.class);
            backIntent.putExtra("name", 1);
            //FilmDetailsActivity.this.setResult(ConstantCode.resultCode, backIntent);
            startActivity(backIntent);*/
            finish();

        }
        return true;

    }
}
